﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;
using System.Net;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HideAllPanel();
        if (IsPostBack == true)
            DoPostBackAction();
        else
            CrossPagePostBackAction();
    }

    private void CrossPagePostBackAction()
    {
        if (this.PreviousPage != null)
        {
            if (this.PreviousPage.IsCrossPagePostBack)
            {
                string actioncode = Request.Params["act"];
                switch (actioncode)
                {
                    case "qmk": panelPhucHoiMatKhau.Visible = true;
                        return;
                }

                if (CheckForLogin())
                {
                    string controlID = Request.Form.Get("__EVENTTARGET");  // or string actionCode = Request.Params.Get("__EVENTTARGET");

                    string userName;
                    Control ctrl = this.PreviousPage.FindControl(controlID);
                    if (ctrl != null)
                        userName = ((LinkButton)ctrl).Text;
                    else
                        userName = Request.Cookies["daugia_user"]["username"];

                    ShowBasicProfileByName(userName);
                    ShowDetailProfileByName(userName);
                }
                else
                    lb1.Text = "Bạn phải đăng nhập.";
            }
        }
        else
            if (Request.Cookies["daugia_user"] != null)
            {
                string userNameLogin = Request.Cookies["daugia_user"]["username"];
                if (userNameLogin.Length == 0)
                {
                    lb1.Text = "Bạn không có quyền xem khu vực này!";
                    lb2.Text = "Vui lòng đăng nhập";
                }
                else
                {
                    ShowBasicProfileByName(userNameLogin);
                    ShowDetailProfileByName(userNameLogin);
                }
            }
    }

    private void DoPostBackAction()
    {
        if(CheckForLogin()==false)
            return;

        string actionCode = Request.Form.Get("__EVENTTARGET");  // or string actionCode = Request.Params.Get("__EVENTTARGET");
        string arguments = Request.Form.Get("__EVENTARGUMENT");

        switch (actionCode)
        {
            case "dangthamgia": CacPhienDangThamGia();
                break;
            case "lichsudaugia": LichSuDauGia(); 
                break;
            case "phiendathang":
                break;
            case "dangsanphammoi": DangSanPhamMoi();
                break;
            case "tknganhang":
                break;
            case "ttcanhan":
                ShowDetailProfileByName(arguments);
                break;
            case "doimatkhau": panelChangePassword.Visible = true;
                break;
            case "emailthongbao":
                break;
            case "phuchoimatkhau": panelPhucHoiMatKhau.Visible = true;
                break;
            case "ctl00$lnkUserLogin":
                UserCustom();
                break;
            case "ctl00$FullBody$calendar": panelDangSanPham.Visible = true;
                break;
            default: 
                break;
        }
    }

    
    private void UserCustom()
    {
        lb1.Text = "user custom";
    }

    private void DangSanPhamMoi()
    {
        panelDangSanPham.Visible = true;
        string maTaiKhoan = GetIDUserLogin();
        if (maTaiKhoan.Length > 0)
        {
            panelDangSanPham.Visible = true;
            LoadLoaiSanPham();
            LoadTinhTrangSanPham();
            return;
        }
        lb1.Text = "Bạn phải đăng nhập.";
    }

    private bool CheckForLogin()
    {
        string maTaiKhoan = GetIDUserLogin();
        if (maTaiKhoan.Length > 0)
            return true;
        return false;
    }

    private string GetIDUserLogin()
    {
        string userid = "";
        if (Request.Cookies["daugia_user"] != null)
                userid = Request.Cookies["daugia_user"]["userid"];
        return userid;
    }

    private void ShowBasicProfileByName(string tenTaiKhoan)
    {
        string strQuery = "Select a.MaTaiKhoan, TenTaiKhoan, HoTen,Avatar from TAIKHOAN a, THONGTINTAIKHOAN b where a.TenTaiKhoan='" + tenTaiKhoan + "' and b.MaTaiKhoan=a.MaTaiKhoan";
        SqlCommand cmd = new SqlCommand(strQuery, Helper.ConnectToDataBase());

        try
        {
            rptBasic.DataSource = cmd.ExecuteReader();
            rptBasic.DataBind();
            Helper.DisposeCommand(ref cmd);
        }
        catch (Exception ex)
        {
            Helper.DisposeCommand(ref cmd);
        }
    }

    private void ShowDetailProfileByName(string userName)
    {
        string strQuery = "Select b.HoTen,b.NgaySinh,b.NoiSinh,b.DiaChi,b.SoDienThoai, b.GioiTinh,b.Email, b.MaTheTinDung, c.TenLoaiTaiKhoan  from TAIKHOAN a, THONGTINTAIKHOAN b, LOAITAIKHOAN c  where a.TenTaiKhoan='" + userName + "' and b.MaTaiKhoan=a.MaTaiKhoan and c.MaLoaiTaiKhoan=a.MaLoaiTaiKhoan";        
        SqlCommand cmd = new SqlCommand(strQuery, Helper.ConnectToDataBase());

        try
        {
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader != null)
            {
                reader.Read();
                txtHoTen.Text = reader.GetString(0);
                DateTime dt = reader.GetDateTime(1);
                txtNgaySinh.Text = dt.Day.ToString() + "/" + dt.Month.ToString() + "/" + dt.Year.ToString();
                txtNoiSinh.Text = reader.GetString(2);
                txtDiaChi.Text = reader.GetString(3);
                txtDienThoai.Text = reader.GetString(4);
                txtGioiTinh.Text = reader.GetString(5);
                txtEmail.Text = reader.GetString(6);
                txtMaTheTinDung.Text = reader.GetString(7);
                txtTenLoaiTaiKhoan.Text = reader.GetString(8);
                panelUserDetail.Visible = true;
            }
        }
        catch (Exception ex)
        {
            Helper.DisposeCommand(ref cmd);
            panelUserDetail.Visible = true;
        }
        Helper.DisposeCommand(ref cmd);
    }

    protected void EnterNewProduct(object sender, EventArgs args)
    {
        string ten = txtTenSanPham.Text.Trim();
        string loai = DropDownListLoaiSanPham.SelectedValue;
        string gia = txtGiaKhoiDiem.Text.Trim();
       
        DateTime ngaydang = DateTime.Now;
        DateTime ngayhethan = calendar.SelectedDate;
        DateTime gkt = DateTime.Parse(txtGioKetThuc.Text);
        ngayhethan += new TimeSpan(gkt.Hour, gkt.Minute, gkt.Second);
        
        string ttrang = DropDownListTinhTrangSP.SelectedValue;
        string mota = txtMoTa.Text.Trim();
        SqlCommand cmd=null;
        try
        {
            List<string> picNames = new List<string>();
            string maTaiKhoan = GetIDUserLogin();
            if (UploadMutiFile(maTaiKhoan, ref picNames) > 0)
            {
                string hinhanh = picNames[0];
                string queryInsert = "insert into SANPHAM values (N'" + ten + "','" + loai + "','" + maTaiKhoan + "','" + gia + "','" + gia + "','" + ngaydang.ToString("s") + "','" + ngayhethan.ToString("s") + "','" + ttrang + "',N'" + mota + "','" + hinhanh +"')";
                cmd = new SqlCommand(queryInsert, Helper.ConnectToDataBase());
                int re = cmd.ExecuteNonQuery();
                Helper.DisposeCommand(ref cmd);
                if (re != -1)
                {
                    panelDangSanPham.Visible = false;
                    lb1.Text = "Đăng sản phẩm thành công.";
                    Label1.Text = "";
                    lb1.Visible = true;
                    int n = InsertMultimediaTable(picNames);
                    InsertBridgeMultimedia(n); // (7) -> (n)
                    panelDangSanPham.Visible = false;
                    ResetFormDangSanPham();
                    return;
                }
            }
        }
        catch(Exception ex)
        {
            lb1.Text = "Đăng sản phẩm thất bại.";
            lb1.Visible = true;
            ResetFormDangSanPham();
        }
        
        lb1.Text="Đăng sản phẩm thất bại.";
        lb1.Visible = true;
        ResetFormDangSanPham();
    }

    private int InsertMultimediaTable(List<string> picNames)
    {
        int n = 0;
        for (int i = 0; i < picNames.Count; i++)
        {
            string MaLoaiMT = GetMaMT(picNames[i]);
            string qInsert = "insert into MULTIMEDIA(TenMT,MaLoaiMT) values ('" + picNames[i] + "','" + MaLoaiMT + "')";
            SqlCommand cmd = new SqlCommand(qInsert, Helper.ConnectToDataBase());
            if(cmd.ExecuteNonQuery() != -1)
                n++;
            Helper.DisposeCommand(ref cmd);
        }
        return n;
    }

    private void InsertBridgeMultimedia(int n)
    {
        int maSanPham = GetMaSanPham();
        List<string> maMT = GetMaMutimedia(n);

        for (int i = 0; i < maMT.Count; i++)
        {
            string qInsert = "insert into SANPHAM_MULTIMEDIA(MaSanPham, MaMT) values('" +maSanPham+ "','" +maMT[i]+ "')";
            SqlCommand cmd = new SqlCommand(qInsert, Helper.ConnectToDataBase());
            cmd.ExecuteNonQuery();
            Helper.DisposeCommand(ref cmd);
        }
    }

    private string GetMaMT(string fileName)
    {
        string ext = Path.GetExtension(fileName);
        return CheckExtension(ext).ToString();
    }

    private int CheckExtension(string ext)
    {
        ext = ext.ToLower();
        switch (ext)
        {
            case ".png":
            case ".jpg":
            case ".jpeg":
            case ".bmp":
            case ".gif": 
                return 1;
            case ".avi":
            case ".wmv":
            case ".mkv":
            case ".mp4": 
                return 2;
        }
        return -1;
    }


    private void ResetFormDangSanPham()
    {
        Label1.Text = "";
        lb2.Text = "";
        calendar.SelectedDate = DateTime.Now;
        txtGiaKhoiDiem.Text = "";
        DropDownListLoaiSanPham.SelectedIndex = 0;
        txtGioKetThuc.Text = "";
        DropDownListTinhTrangSP.SelectedIndex = 0;
        txtMoTa.Text = "";
        txtTenSanPham.Text = "";
    }

    private List<string> GetMaMutimedia(int n)
    {
        List<string> l = new List<string>();
        string qSelectMSP = "SELECT TOP " + n.ToString() + " MaMT FROM MULTIMEDIA ORDER BY MaMT DESC";
        SqlCommand cmd = new SqlCommand(qSelectMSP, Helper.ConnectToDataBase());
        SqlDataReader reader = cmd.ExecuteReader();

        int maMT;
        if (reader != null)
        {
            while (reader.Read())
            {
                maMT = reader.GetInt32(0);
                l.Add(maMT.ToString());
            }
        }
        Helper.DisposeCommand(ref cmd);
        return l;
    }

    private int GetMaSanPham()
    {
        string qSelectMSP = "SELECT TOP 1 MaSanPham FROM SANPHAM ORDER BY NgayDang DESC";
        SqlCommand cmd = new SqlCommand(qSelectMSP, Helper.ConnectToDataBase());
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader != null)
        {
            reader.Read();
            return reader.GetInt32(0);
        }

        Helper.DisposeCommand(ref cmd);
        return -1;
    }

    private void LoadTinhTrangSanPham()
    {
        string query = "select * from TINHTRANGSANPHAM";
        SqlCommand cmd = new SqlCommand(query, Helper.ConnectToDataBase());
        DropDownListTinhTrangSP.DataSource = cmd.ExecuteReader();
        DropDownListTinhTrangSP.DataTextField = "TenTinhTrangSanPham";
        DropDownListTinhTrangSP.DataValueField = "MaTinhTrangSanPham";
        DropDownListTinhTrangSP.DataBind();
        Helper.DisposeCommand(ref cmd);
    }

    private void LoadLoaiSanPham()
    {
        string query = "select MaLoaiSanPham, TenLoaiSanPham from LOAISANPHAM";
        SqlCommand cmd = new SqlCommand(query, Helper.ConnectToDataBase());
        DropDownListLoaiSanPham.DataSource = cmd.ExecuteReader();
        DropDownListLoaiSanPham.DataTextField = "TenLoaiSanPham";
        DropDownListLoaiSanPham.DataValueField = "MaLoaiSanPham";
        DropDownListLoaiSanPham.DataBind();
        Helper.DisposeCommand(ref cmd);
    }
    
    #region Upload file
    protected void btnAttach_Click(object sender, System.EventArgs e)
    {
        // Save the attached file to fileName variable
        StatusLabel.Text = "";
        Label1.Text = "";
        string fileName = FileUpload.PostedFile.FileName;
        if (fileName == "")
            return;
        if (CheckExtension(Path.GetExtension(fileName)) == -1)
        {
            StatusLabel.Text = "Chỉ được upload hình ảnh và video.";
                return;
        }

        // If the counter is null then create one with default value equal to 0
        if (ViewState["i"] == null)
        {
            ViewState["i"] = 0;
        }
        // Check if a file is selected 
        if (fileName != null || fileName != string.Empty)
        {
            // Add  it to the collection
            ListBox1.Items.Add(FileUpload.PostedFile.FileName);

            // Save an index for each selected file
            int i = Convert.ToInt32(ViewState["i"]);

            // Save the fileupload control into a different session
            Session["myupload" + i] = FileUpload;

            // Increment the counter
            i++;

            // Set the ViewSate to the latest counter value.
            ViewState["i"] = i;

        }
    }


    protected int UploadMutiFile(string maTaiKhoan, ref List<string> picNames)
    {
        ///int sessionCount = Convert.ToInt32(ViewState["i"]);

        int nSuccess = 0;
        int sessionCount = Session.Count;
        for (int i = sessionCount - 1; i >= 0; i--)
        {
            if (sessionCount <= 10)
            {
                HtmlInputFile hif = (HtmlInputFile)Session["myupload" + i];
                if (hif.PostedFile.ContentLength <= 500000)
                {
                    string storePath = Server.MapPath("~") + "/productImgs/" + maTaiKhoan + "/";
                    if (!Directory.Exists(storePath))
                        Directory.CreateDirectory(storePath);

                    picNames.Add(Path.GetFileName(hif.PostedFile.FileName));
                    hif.PostedFile.SaveAs(storePath + "/" + picNames[picNames.Count-1]);
                    Label1.Text = "Your Files are uploaded successfully";
                    ListBox1.Items.Clear();
                    nSuccess++;
                }
                else
                    Label1.Text = "An error occured";
            }
            else
                Label1.Text = "You have exceeded the maximum number of files to be uploaded (10)";
        }

        Session.RemoveAll();
        return nSuccess;
    }

    protected void btnDelete_Click(object sender, System.EventArgs e)
    {
        if (ListBox1.SelectedIndex > -1)
        {
            int uploadedFileIndex = ListBox1.SelectedIndex;
            Session.Remove("myupload" + uploadedFileIndex);
            ListBox1.Items.Remove(ListBox1.SelectedValue);
        }
    }
    # endregion
    
    private void HideAllPanel()
    {
        panelUserDetail.Visible = false;
        panelChangePassword.Visible = false;
        panelThamGiaDauGia.Visible = false;
        lb1.Text = "";
        lb2.Text = "";
    }

    protected void UpdateUserProfile(object sender, EventArgs arrgs)
    {
        string ten = txtHoTen.Text;
        string ngaysinh = DateTime.Parse(txtNgaySinh.Text).ToString("s");
        string noisinh = txtNoiSinh.Text;
        string diachi = txtDiaChi.Text;
        string dienthoai = txtDienThoai.Text;
        string gioitinh = txtGioiTinh.Text;
        string matindung = txtMaTheTinDung.Text;
        string id = GetIDUserLogin();

        string qUpdate = "update THONGTINTAIKHOAN set HoTen=N'"+ten+"',NgaySinh='"+ngaysinh+"',NoiSinh=N'"+noisinh+"',DiaChi=N'"+diachi+"',SoDienThoai='"+dienthoai+"',MaTheTinDung='"+matindung+"',GioiTinh=N'"+gioitinh+"' where MaTaiKhoan="+id;
        SqlCommand cmd = new SqlCommand(qUpdate, Helper.ConnectToDataBase());
        int re = cmd.ExecuteNonQuery();
        if (re != -1)
            lb1.Text = "Cập nhật thành công.";
        else
            lb1.Text = "Cập nhật thất bại >.<";
        lb1.Visible = true;
    }

    protected void ChangeUserPassword(object sender, EventArgs args)
    {
        string newPass1 = txtNewPass1.Text;
        string newPass2 = txtNewPass2.Text;
        lb1.Text = "Có lỗi xảy ra. Mật khẩu không thay đổi.";
        if (newPass1 == newPass2)
        {
            string maTaiKhoan = GetIDUserLogin(); 
            string qSelectPassword = "select MatKhau from TAIKHOAN where MaTaiKhoan=" + maTaiKhoan;
            SqlCommand cmd = new SqlCommand(qSelectPassword, Helper.ConnectToDataBase());
            SqlDataReader rd = cmd.ExecuteReader();

            string oldPass0 = txtOldPass.Text;
            if (rd != null)
            {
                rd.Read();
                oldPass0 = rd.GetString(0);
                string oldPass1 = txtOldPass.Text;
                if (oldPass0 == oldPass1)
                {
                    string qUpdate = "update TAIKHOAN set MatKhau=" + newPass1 + " where MaTaiKhoan="+maTaiKhoan;
                    SqlCommand cmd2 = new SqlCommand(qUpdate, Helper.ConnectToDataBase());
                    int re = cmd2.ExecuteNonQuery();
                    if (re != -1)
                    {
                        lb1.Text = "Mật khẩu đã được thay đổi.";
                        panelChangePassword.Visible = false;
                    }
                    Helper.DisposeCommand(ref cmd2);
                }
            }
            Helper.DisposeCommand(ref cmd);
        }

        txtOldPass.Text = "";
        txtNewPass1.Text = "";
        txtNewPass2.Text = "";
    }

    

    protected void PhucHoiMatKhau(object sender, EventArgs args)
    {
        lb1.Text = "Đã có lỗi xảy ra. Thử lại sau vài giây.";
        string userid="";
        if (CheckEmailQuenMatKhau(ref userid) == true)
        {
            string newpass = Helper.GetRandomString();
            if (ChangeRandomPassword(userid, newpass))
            {
                string qSelect = "select HoTen,Email from THONGTINTAIKHOAN where MaTaiKhoan=" + userid;
                SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
                SqlDataReader rd = cmd.ExecuteReader();
                if (rd != null)
                {
                    rd.Read();
                    string hoten = rd.GetString(0);
                    string toEmail = rd.GetString(1);
                    string subject = "[C3-Đấu giá]: Phục hồi mật khẩu";
                    string message = "Chào " + hoten + "!. Bạn vừa yêu cầu thay đổi mật khẩu. Mật khẩu mới của bạn là: '"+newpass+"'. Hãy đổi mật khẩu ngay lần đăng nhập tiếp theo. Cảm ơn đã tham gia C3-Daugia. Chúc bạn vui vẻ!";
                    Helper.SendGMail(toEmail, subject, message);
                    lb1.Text = "Mật khẩu mới của bạn đã được gởi tới địa chỉ email: "+toEmail+".Hãy đổi mật khẩu ngay lần đăng nhập tiếp theo. Cảm ơn đã tham gia C3-Daugia. Chúc bạn vui vẻ!" ;
                    panelPhucHoiMatKhau.Visible = false;
                }
            }
        }
    }

    private bool CheckEmailQuenMatKhau(ref string userid)
    {
        string email = txtEmailQuenMatKhau.Text;
        string qSelect = "select MaTaiKhoan from THONGTINTAIKHOAN where Email='" + email + "'" ;
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        SqlDataReader rd = cmd.ExecuteReader();
        if (rd != null)
        {
            if (rd.Read())
            {
                userid = rd.GetInt32(0).ToString();
                return true;
            }
            else
                lb1.Text = "Địa chỉ email bạn nhập không đúng. Lưu ý đây là email bạn dùng khi đăng kí thành viên với diễn đàn C3-DauGia";
        }
        return false;
    }

    private bool ChangeRandomPassword(string userid, string newpass)
    {
        string qUpdate = "update TAIKHOAN set MatKhau='"+newpass+"' where MaTaiKhoan="+userid;
        SqlCommand cmd = new SqlCommand(qUpdate, Helper.ConnectToDataBase());
        if(cmd.ExecuteNonQuery() != -1)
            return true;

        lb1.Text = "Đã có lỗi xảy ra. Thử lại sau vài giây.";
        return false;
        
    }
    
    private void LichSuDauGia()
    {
        string userid = GetIDUserLogin();
        string qSelect = "Select a.MaSanPham,a.TenSanPham,a.NgayHetHan,a.GiaHienTai from SANPHAM a, CHITIETDAUGIA b where  b.MaTaiKhoan="+userid+" and a.MaSanPham=b.MaSanPham group by a.MaSanPham,a.TenSanPham,a.NgayHetHan,a.GiaHienTai order by NgayHetHan desc";
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        try
        {
            DataGrid1.DataSource = cmd.ExecuteReader();
            DataGrid1.DataBind();
            Helper.DisposeCommand(ref cmd);
        }
        catch (Exception)
        {
            Helper.DisposeCommand(ref cmd);
        }
        panelThamGiaDauGia.Visible = true;
    }

    private void CacPhienDangThamGia()
    {
        this.DataGrid1.DataSource = null;
        
        string userid = GetIDUserLogin();
        string qSelect = "Select a.MaSanPham,a.TenSanPham,a.NgayHetHan,a.GiaHienTai from SANPHAM a, CHITIETDAUGIA b where  b.MaTaiKhoan=" + userid + " and a.MaSanPham=b.MaSanPham and DATEDIFF(day, NgayHetHan, GetDate()) <= 0 group by a.MaSanPham,a.TenSanPham,a.NgayHetHan,a.GiaHienTai order by NgayHetHan desc";
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        try
        {
            DataGrid1.DataSource = cmd.ExecuteReader();
            DataGrid1.DataBind();
            Helper.DisposeCommand(ref cmd);
        }
        catch (Exception)
        {
            Helper.DisposeCommand(ref cmd);
        }
        panelThamGiaDauGia.Visible = true;  
    }


}
